/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/<a href="https://www.kaaction.com">KAA</a>"><a href="https://www.kaaction.com">KAA</a></a> All rights reserved.
 */
package com.kaaction.modules.ka.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.kaaction.common.config.Global;
import com.kaaction.common.persistence.Page;
import com.kaaction.common.web.BaseController;
import com.kaaction.common.utils.DateUtils;
import com.kaaction.common.utils.StringUtils;
import com.kaaction.common.utils.excel.ExportExcel;
import com.kaaction.modules.ka.entity.BasicGoods;
import com.kaaction.modules.ka.entity.ProductManage;
import com.kaaction.modules.ka.entity.ProductManageDetails;
import com.kaaction.modules.ka.entity.Statistics;
import com.kaaction.modules.ka.service.BasicGoodsService;
import com.kaaction.modules.ka.service.KaColorService;
import com.kaaction.modules.ka.service.KaSizeService;
import com.kaaction.modules.ka.service.ProductManageService;

/**
 * 货品管理Controller
 * @author huanghaiming
 * @version 2017-04-25
 */
@Controller
@RequestMapping(value = "${adminPath}/ka/productManage")
public class ProductManageController extends BaseController {

	@Autowired
	private ProductManageService productManageService;
	
	@Autowired
	private BasicGoodsService basicGoodsService;
	
	@Autowired
	private KaSizeService  sizeService;
	
	@Autowired
	private KaColorService  colorService;
	
	@ModelAttribute
	public ProductManage get(@RequestParam(required=false) String id) {
		
		ProductManage entity = null;
		
		if (StringUtils.isNotBlank(id)){
			entity = productManageService.get(id);
			
			entity.setListPro(basicGoodsService.getProductCode(entity)) ;
			
			/*BasicGoods basicGoods  = basicGoodsService.getAttr(entity);
			String sizeId = basicGoods.getSizeId();
			String colorId = basicGoods.getColorId();
			
			List<String> ListSize =  new ArrayList<String>(); 
			List<String> ListColor =  new ArrayList<String>(); 
			
			
			if(StringUtils.isNotBlank(sizeId)){
				String[] sizeIds = sizeId.split(",");
				for(int i=0;i<sizeIds.length;i++){
					ListSize.add(sizeIds[i]);
				}
				entity.setListSize(sizeService.selSize(ListSize));
			}
			
			if(StringUtils.isNotBlank(colorId)){
				String[] colorIds = colorId.split(",");
				for(int i=0;i<colorIds.length;i++){
					ListColor.add(colorIds[i]);
				}
				entity.setListColor(colorService.selColor(ListColor));
			}*/
			
		}
		if (entity == null){
			entity = new ProductManage();
			entity.setInstockDate(new Date());
		}
		return entity;
	}
	
	@RequiresPermissions("ka:productManage:view")
	@RequestMapping(value = {"list", ""})
	public String list(ProductManage productManage, HttpServletRequest request, HttpServletResponse response, Model model) {
		productManage.getSqlMap().put("dsf", "and a.state in ('0','1','2','3','4','6')");
		Statistics statistics =productManageService.selStatistics(productManage);
		model.addAttribute("statistics", statistics);
		Page<ProductManage> page = productManageService.findPage(new Page<ProductManage>(request, response), productManage); 
		model.addAttribute("page", page);
		return "modules/ka/productManageList";
	}

	@RequiresPermissions("ka:productManage:view")
	@RequestMapping(value = "form")
	public String form(ProductManage productManage, Model model) {
		model.addAttribute("productManage", productManage);
		return "modules/ka/productManageForm";
	}

	@RequiresPermissions("ka:productManage:edit")
	@RequestMapping(value = "save")
	public String save(ProductManage productManage, Model model, RedirectAttributes redirectAttributes) {
		if (!beanValidator(model, productManage)){
			return form(productManage, model);
		}
		
		if(StringUtils.isBlank(productManage.getId())){
			
			List<ProductManageDetails> listSku = productManage.getEventSkuList();
			
			productManage.setListPro(basicGoodsService.getProductCode(productManage)) ;
			
			BasicGoods basicGoods  = basicGoodsService.getAttr(productManage);
			String sizeId = basicGoods.getSizeId();
			String colorId = basicGoods.getColorId();
			
			List<String> ListSize =  new ArrayList<String>(); 
			List<String> ListColor =  new ArrayList<String>(); 
			
			
			if(StringUtils.isNotBlank(sizeId)){
				String[] sizeIds = sizeId.split(",");
				for(int i=0;i<sizeIds.length;i++){
					ListSize.add(sizeIds[i]);
				}
				productManage.setListSize(sizeService.selSize(ListSize));
			}
			
			if(StringUtils.isNotBlank(colorId)){
				String[] colorIds = colorId.split(",");
				for(int i=0;i<colorIds.length;i++){
					ListColor.add(colorIds[i]);
				}
				productManage.setListColor(colorService.selColor(ListColor));
			}
			
			
			if(listSku.size()==0){
				model.addAttribute("message", "属性添加不能为空");
				return form(productManage, model);
			}
			
			
		}
		
		
		productManageService.save(productManage);
		addMessage(redirectAttributes, "保存货品管理成功");
		return "redirect:"+Global.getAdminPath()+"/ka/productManage/?repage";
	}
	
	@RequiresPermissions("ka:productManage:delete")
	@RequestMapping(value = "delete")
	public String delete(ProductManage productManage, RedirectAttributes redirectAttributes) {
		productManageService.delete(productManage);
		addMessage(redirectAttributes, "删除货品管理成功");
		return "redirect:"+Global.getAdminPath()+"/ka/productManage/?repage";
	}
	
	@RequiresPermissions("ka:productManage:delete")
	@RequestMapping(value = "deleteAll")
	public String deleteAll(ProductManage productManage, RedirectAttributes redirectAttributes) {
		productManageService.deleteAll(productManage);
		addMessage(redirectAttributes, "删除货品管理成功");
		return "redirect:"+Global.getAdminPath()+"/ka/productManage/?repage";
	}
	
	/**
	 * 编辑初始化
	 * @param productManage
	 * @param model
	 * @return
	 */
	@RequiresPermissions("ka:productManage:view")
	@RequestMapping(value = "savaForm")
	public String savaForm(ProductManage productManage, Model model) {
		model.addAttribute("productManage", productManage);
		return "modules/ka/productManageSaveForm";
	}
	
	/**
	 * 获取供应商下的商品编码
	 * @param productManage
	 * @param model
	 * @return
	 */
	@RequiresPermissions("ka:productManage:view")
	@RequestMapping(value = "getProductCode")
	public String getProductCode(ProductManage productManage, Model model) {
		productManage.setListPro(basicGoodsService.getProductCode(productManage)) ;
		return form(productManage,model);
	}
	
	/**
	 * 获取该商品下所有属性
	 * @param productManage
	 * @param model
	 * @return
	 */
	@RequiresPermissions("ka:productManage:view")
	@RequestMapping(value = "getAttr")
	public String getAttr(ProductManage productManage, Model model) {
		BasicGoods basicGoods  = basicGoodsService.getAttr(productManage);
		productManage.setListPro(basicGoodsService.getProductCode(productManage)) ;
		productManage.setCategoryId(basicGoods.getCategoryId());
		productManage.setPrice(basicGoods.getInstockPrice());
		productManage.setSalesPrice(basicGoods.getSalePrice());
		productManage.setProductCode(productManage.getProductCode());
		
		String sizeId = basicGoods.getSizeId();
		String colorId = basicGoods.getColorId();
		
		List<String> ListSize =  new ArrayList<String>(); 
		List<String> ListColor =  new ArrayList<String>(); 
		
		
		if(StringUtils.isNotBlank(sizeId)){
			String[] sizeIds = sizeId.split(",");
			for(int i=0;i<sizeIds.length;i++){
				ListSize.add(sizeIds[i]);
			}
			productManage.setListSize(sizeService.selSize(ListSize));
		}
		
		if(StringUtils.isNotBlank(colorId)){
			String[] colorIds = colorId.split(",");
			for(int i=0;i<colorIds.length;i++){
				ListColor.add(colorIds[i]);
			}
			productManage.setListColor(colorService.selColor(ListColor));
		}
		
		return form(productManage,model);
	}
	
	/**
	 * 导出货品管理数据
	 * @param user
	 * @param request
	 * @param response
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("ka:productManage:view")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public String exportFile(ProductManage productManage, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "货品管理数据"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            productManage.getSqlMap().put("dsf", "and a.state in ('0','1','2','3','4','6')");
            List<ProductManage> list = productManageService.findProductManage(productManage);
    		new ExportExcel("货品管理数据", ProductManage.class).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导出货品管理数据失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/ka/salesReturn/?repage";
    }
	
	
	@RequiresPermissions("ka:productManage:view")
	@RequestMapping(value = "stayPutawayForm")
	public String stayputawayForm(ProductManage productManage, Model model) {
		model.addAttribute("productManage", productManage);
		return "modules/ka/stayPutawayForm";
	}
	
	/**
	 * 货品质检上架
	 * @param productManage
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("ka:productManage:edit")
	@RequestMapping(value = "stayPutaway")
	public String stayPutaway(ProductManage productManage, Model model, RedirectAttributes redirectAttributes) {
		
		int cnt = productManageService.getCount(productManage);//是否超出质检数量
		
		if(cnt==0){
			model.addAttribute("message", "超出库存质检数量");
			return stayputawayForm(productManage, model);
		}
		productManage.setState("1");
		productManageService.putawayProcess(productManage);
		addMessage(redirectAttributes, "库存质检成功");
		return "redirect:"+Global.getAdminPath()+"/ka/productManage/?repage";
	}
	
	/**
	 * 货品质检不通过
	 * @param productManage
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("ka:productManage:edit")
	@RequestMapping(value = "noPass")
	public String noPass(ProductManage productManage, Model model, RedirectAttributes redirectAttributes) {
		
		int cnt = productManageService.getCount(productManage);//是否超出质检不通数量
		
		if(cnt==0){
			model.addAttribute("message", "超出库存质检不通过数量");
			return putawayForm(productManage, model);
		}
		productManage.setState("5");
		productManageService.putawayProcess(productManage);
		addMessage(redirectAttributes, "库存质检不通过成功");
		return "redirect:"+Global.getAdminPath()+"/ka/productManage/?repage";
	}
	
	@RequiresPermissions("ka:productManage:view")
	@RequestMapping(value = "putawayForm")
	public String putawayForm(ProductManage productManage, Model model) {
		model.addAttribute("productManage", productManage);
		return "modules/ka/putawayForm";
	}
	
	/**
	 * 货品上架
	 * @param productManage
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("ka:productManage:edit")
	@RequestMapping(value = "putaway")
	public String putaway(ProductManage productManage, Model model, RedirectAttributes redirectAttributes) {
		
		int cnt = productManageService.getCount(productManage);//是否超出上架数量
		
		if(cnt==0){
			model.addAttribute("message", "超出上架数量");
			return putawayForm(productManage, model);
		}
		productManage.setState("2");
		productManageService.putawayProcess(productManage);
		addMessage(redirectAttributes, "库存上架成功");
		return "redirect:"+Global.getAdminPath()+"/ka/productManage/?repage";
	}
	
	@RequiresPermissions("ka:productManage:view")
	@RequestMapping(value = "workOffForm")
	public String workOffForm(ProductManage productManage, Model model) {
		model.addAttribute("productManage", productManage);
		return "modules/ka/workOffForm";
	}
	
	/**
	 * 货品售出
	 * @param productManage
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("ka:productManage:edit")
	@RequestMapping(value = "workOff")
	public String workOff(ProductManage productManage, Model model, RedirectAttributes redirectAttributes) {
		
		int cnt = productManageService.getCount(productManage);//是否超出售出数量
		
		if(cnt==0){
			model.addAttribute("message", "超出售出数量");
			return workOffForm(productManage, model);
		}
		productManage.setState("3");
		productManageService.putawayProcess(productManage);
		addMessage(redirectAttributes, "库存售出成功");
		return "redirect:"+Global.getAdminPath()+"/ka/productManage/?repage";
	}
	
	@RequiresPermissions("ka:productManage:view")
	@RequestMapping(value = "soldOutForm")
	public String soldOutForm(ProductManage productManage, Model model) {
		model.addAttribute("productManage", productManage);
		return "modules/ka/soldOutForm";
	}
	
	/**
	 * 货品下架
	 * @param productManage
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("ka:productManage:edit")
	@RequestMapping(value = "soldOut")
	public String soldOut(ProductManage productManage, Model model, RedirectAttributes redirectAttributes) {
		
		int cnt = productManageService.getCount(productManage);//是否超出下架数量
		
		if(cnt==0){
			model.addAttribute("message", "超出下架数量");
			return soldOutForm(productManage, model);
		}
		productManage.setState("4");
		productManageService.putawayProcess(productManage);
		addMessage(redirectAttributes, "库存下架成功");
		return "redirect:"+Global.getAdminPath()+"/ka/productManage/?repage";
	}
	
	@RequiresPermissions("ka:productManage:view")
	@RequestMapping(value = "outboundInspecForm")
	public String outboundInspecForm(ProductManage productManage, Model model) {
		model.addAttribute("productManage", productManage);
		return "modules/ka/outboundInspecForm";
	}
	
	/**
	 * 货品售出质检
	 * @param productManage
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("ka:productManage:edit")
	@RequestMapping(value = "outboundInspec")
	public String outboundInspec(ProductManage productManage, Model model, RedirectAttributes redirectAttributes) {
		
		int cnt = productManageService.getCount(productManage);//是否出库质检数量
		
		if(cnt==0){
			model.addAttribute("message", "超出售出质检数量");
			return outboundInspecForm(productManage, model);
		}
		productManageService.outboundInspec(productManage);
		addMessage(redirectAttributes, "库存售出质检成功");
		return "redirect:"+Global.getAdminPath()+"/ka/productManage/?repage";
	}
	
	/**
	 * 判断是否已新增待质检状态
	 * @param ids
	 * @return
	 */
	@RequiresPermissions("ka:productManage:edit")
	@RequestMapping(value={"/checkQuality"}, method=RequestMethod.POST)
	@ResponseBody
	public  Map<String,Object> checkQuality(@RequestParam("ids") String ids){
		return productManageService.checkQuality(ids,"0","已新增待质检状态才能进行批量质检");
	}
	
	/**
	 * 货品批量质检入库
	 * @param productManage
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("ka:productManage:edit")
	@RequestMapping(value = "batchQualityPutaway")
	public String batchQualityPutaway(ProductManage productManage, Model model, RedirectAttributes redirectAttributes) {
		productManageService.batchPutaway(productManage,"1","0");
		addMessage(redirectAttributes, "货品批量质检入库成功");
		return "redirect:"+Global.getAdminPath()+"/ka/productManage/?repage";
	}
	
	/**
	 * 判断是否已入库待上架和已下架状态
	 * @param ids
	 * @return
	 */
	@RequiresPermissions("ka:productManage:edit")
	@RequestMapping(value={"/checkPutaway"}, method=RequestMethod.POST)
	@ResponseBody
	public  Map<String,Object> checkPutaway(@RequestParam("ids") String ids){
		return productManageService.checkQuality(ids,"1,4","已入库待上架和已下架状态才能进行批量上架");
	}
	
	/**
	 * 货品批量上架
	 * @param productManage
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("ka:productManage:edit")
	@RequestMapping(value = "batchPutaway")
	public String batchPutaway(ProductManage productManage, Model model, RedirectAttributes redirectAttributes) {
		productManageService.batchPutaway(productManage,"2","1,4");
		addMessage(redirectAttributes, "批量上架成功");
		return "redirect:"+Global.getAdminPath()+"/ka/productManage/?repage";
	}
	
	/**
	 * 判断是否已上架状态
	 * @param ids
	 * @return
	 */
	@RequiresPermissions("ka:productManage:edit")
	@RequestMapping(value={"/checkSoldOut"}, method=RequestMethod.POST)
	@ResponseBody
	public  Map<String,Object> checkSoldOut(@RequestParam("ids") String ids){
		return productManageService.checkQuality(ids,"2","已上架状态才能进行批量售出");
	}
	
	/**
	 * 货品批量售出初始化
	 * @param productManage
	 * @param model
	 * @return
	 */
	@RequiresPermissions("ka:productManage:view")
	@RequestMapping(value = "batchSoldOutForm")
	public String batchSoldOutForm(ProductManage productManage, Model model) {
		productManage.setColumnList(productManageService.selectBatchSoldOut(productManage));
		model.addAttribute("productManage", productManage);
		return "modules/ka/batchSoldOutForm";
	}
	
	/**
	 * 货品批量售出
	 * @param productManage
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("ka:productManage:edit")
	@RequestMapping(value = "batchSoldOut")
	public String batchSoldOut(ProductManage productManage, Model model, RedirectAttributes redirectAttributes) {
		
		List<ProductManage> pms = productManage.getColumnList();
		int a =0;
		for(ProductManage pm :pms){
			int cnt = productManageService.getCount(pm);
			if(cnt==0){
				a++;
				break;
			}
		}
		
		if(a>0){
			model.addAttribute("message", "超出出库质检数量");
			return batchSoldOutFrm(productManage, model);
		}
		
		productManageService.batchSoldOut(productManage);
		addMessage(redirectAttributes, "货品批量售出成功");
		return "redirect:"+Global.getAdminPath()+"/ka/productManage/?repage";
	}
	
	/**
	 * 货品批量售出初始化
	 * @param productManage
	 * @param model
	 * @return
	 */
	@RequiresPermissions("ka:productManage:view")
	@RequestMapping(value = "batchSoldOutFrm")
	public String batchSoldOutFrm(ProductManage productManage, Model model) {
		model.addAttribute("productManage", productManage);
		return "modules/ka/batchSoldOutForm";
	}
	
	/**
	 * 判断是否已售出待质检状态
	 * @param ids
	 * @return
	 */
	@RequiresPermissions("ka:productManage:edit")
	@RequestMapping(value={"/checkQualityOut"}, method=RequestMethod.POST)
	@ResponseBody
	public  Map<String,Object> checkQualityOut(@RequestParam("ids") String ids){
		return productManageService.checkQuality(ids,"2","已上架状态才能进行批量质检出库");
	}
	
	/**
	 * 货品批量质检出库初始化
	 * @param productManage
	 * @param model
	 * @return
	 */
	@RequiresPermissions("ka:productManage:view")
	@RequestMapping(value = "batchQualityOutForm")
	public String batchQualityOutForm(ProductManage productManage, Model model) {
		productManage.setColumnList(productManageService.selectBatchOut(productManage));
		model.addAttribute("productManage", productManage);
		return "modules/ka/batchQualityOutForm";
	}
	
	/**
	 * 货品批量质检出库
	 * @param productManage
	 * @param model
	 * @param redirectAttributes
	 * @return
	 */
	@RequiresPermissions("ka:productManage:edit")
	@RequestMapping(value = "batchQualityOut")
	public String batchQualityOut(ProductManage productManage, Model model, RedirectAttributes redirectAttributes) {
		
		List<ProductManage> pms = productManage.getColumnList();
		int a =0;
		for(ProductManage pm :pms){
			Integer num = pm.getNum();
			pm.setNum(pm.getAmount());
			int cnt = productManageService.getCount(pm);
			pm.setNum(num);
			if(cnt==0){
				a++;
				break;
			}
		}
		
		if(a>0){
			model.addAttribute("message", "超出售出质检出库数量");
			return batchQualityOutFrm(productManage, model);
		}
		
		productManageService.batchQualityOut(productManage);
		addMessage(redirectAttributes, "货品批量售出质检出库成功");
		return "redirect:"+Global.getAdminPath()+"/ka/productManage/?repage";
	}
	
	/**
	 * 货品批量售出初始化
	 * @param productManage
	 * @param model
	 * @return
	 */
	@RequiresPermissions("ka:productManage:view")
	@RequestMapping(value = "batchQualityOutFrm")
	public String batchQualityOutFrm(ProductManage productManage, Model model) {
		model.addAttribute("productManage", productManage);
		return "modules/ka/batchQualityOutForm";
	}
	
}